#include "HeroLevelUpCacheData.h"

HeroLevelUpCacheData* HeroLevelUpCacheData::mInstance = NULL;

void HeroLevelUpCacheData::CreateInstance()
{
	if (mInstance == nullptr)
	{
		mInstance = new HeroLevelUpCacheData();
	}
}

HeroLevelUpCacheData* HeroLevelUpCacheData::GetInstance()
{
	return mInstance;
}

HeroLevelUpCacheData::HeroLevelUpCacheData()
	: m_maxCount(0)
{
}

HeroLevelUpCacheData::~HeroLevelUpCacheData()
{
	Clear();
}

bool HeroLevelUpCacheData::Reload()
{
	_safe_guard_begin;

	Clear();

	Initialization();

	_safe_guard_end;

	return false;
}

void HeroLevelUpCacheData::Clear()
{
	_safe_guard_begin;

	auto itor = m_mapCacheData.begin();
	for (; itor != m_mapCacheData.end(); ++itor)
	{
		_safe_delete(itor->second);
	}

	m_mapCacheData.clear();

	_safe_guard_end;
}

bool HeroLevelUpCacheData::Initialization()
{
	_safe_guard_begin;

	Json::Value _jv = ReadJsonFile("./data/hero/heroLevelUp.json");
	if (_jv == Json::nullValue)
	{
		LOG_ERROR("default","ReadJsonFile -> data/hero/heroLevelUp.json failed ......");
		return false;
	}

	m_maxCount = _jv.size();

	Json::Value::Members _tmp = _jv.getMemberNames();
	uint32_t _size = (uint32_t)(_tmp.size());
	for (uint32_t i = 0; i < _size; ++i)
	{
		uint32_t _idx = (uint32_t)atoi(_tmp[i].c_str());

		AddData(_idx, _jv[_tmp[i]]);
	}

	return true;

	_safe_guard_end;

	return false;
}


void HeroLevelUpCacheData::AddData(uint32_t id, Json::Value& jm)
{
	_safe_guard_begin;

	auto itor = m_mapCacheData.find(id);
	if (itor == m_mapCacheData.end())
	{
		HeroLevelUp* p = new HeroLevelUp;
		_safe_check(p);

		p->mId = jm["id"].asUInt();
		p->mExp = jm["exp"].asUInt();
		p->mSkillLimit = jm["skill_limit"].asUInt();
		p->mSkillCeiling = jm["skill_ceiling"].asUInt();
		p->mGrade = jm["grade"].asUInt();

		m_mapCacheData[id] = p;
	}

	_safe_guard_end;
}


HeroLevelUp* HeroLevelUpCacheData::GetData(uint32_t id)
{
	_safe_guard_begin;

	auto itor = m_mapCacheData.find(id);
	if (itor != m_mapCacheData.end())
	{
		return itor->second;
	}
	_safe_guard_end;

	return nullptr;
}

bool HeroLevelUpCacheData::GetDataJsonString(uint32_t id, Json::Value& _jm)
{
	_safe_guard_begin;

	HeroLevelUp* p = GetData(id);
	if (nullptr == p)
	{
		LOG_ERROR("default","Error8");
		return false;
	}

	_jm.clear();

	_jm["id"] = Json::Value(p->mId);
	_jm["exp"] = Json::Value(p->mExp);
	_jm["skill_limit"] = Json::Value(p->mSkillLimit);
	_jm["skill_ceiling"] = Json::Value(p->mSkillCeiling);
	_jm["grade"] = Json::Value(p->mGrade);

	_safe_guard_end;

	return true;
}

uint32_t HeroLevelUpCacheData::GetDataCount()
{
	_safe_guard_begin;

	return m_maxCount;

	_safe_guard_end;
}

